package com.study.io.nio.demo.reactor;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 多reactor Acceptor
 *
 * @author wuxj
 */
public class MthreadAcceptor implements Runnable {

    final Selector[] selectors;
    final ServerSocketChannel serverSocket;
    int next = 0;

    /**
     * Acceptor初始化
     *
     * @param selectors
     * @param serverSocket
     */
    public MthreadAcceptor(Selector[] selectors, ServerSocketChannel serverSocket) {
        this.selectors = selectors;
        this.serverSocket = serverSocket;
    }

    @Override
    public synchronized void run() {
        /**
         * 主selector负责accept
         */
        try {
            SocketChannel connection = serverSocket.accept();
            if (connection != null) {
                /**
                 * 选个subReactor去负责接收到的connection
                 */
                //new Handler(selectors[next], connection);
                new MthreadHandler(selectors[next], connection);
            }
            if (++next == selectors.length) {
                next = 0;
            }
        } catch (IOException ex) { /* ... */ }


    }
}
